/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.icanci.snow.spring.mvc;

import cn.icanci.snow.spring.mvc.processor.RequestProcessor;
import cn.icanci.snow.spring.mvc.render.ResultRender;
import cn.icanci.snow.spring.mvc.render.impl.DefaultResultRender;
import cn.icanci.snow.spring.mvc.render.impl.InternalErrorResultRender;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 以责任链的模式执行注册的请求处理器
 * 委派给特定的Render实例对处理后的结果进行渲染
 * 
 * @author icanci
 * @date Created in 2021/05/19 17:18
 * @version 1.0
 */
@Data
@Slf4j
public class RequestProcessorChain {

    /**
     * 请求处理迭代器
     */
    private Iterator<RequestProcessor> requestProcessorIterator;
    /**
     * 请求request
     */
    private HttpServletRequest         request;
    /**
     * 请求的response
     */
    private HttpServletResponse        response;
    /**
     * http请求的方法
     */
    private String                     requestMethod;
    /**
     * http 请求路径
     */
    private String                     requestPath;
    /**
     * 请求状态码
     */
    private int          responseCode;
    /**
     * 请求结果渲染器实例
     */
    private ResultRender resultRender;

    /**
     * 构造函数
     * @param iterator 请求处理迭代器
     * @param req 请求 
     * @param resp 相应
     */
    public RequestProcessorChain(Iterator<RequestProcessor> iterator, HttpServletRequest req, HttpServletResponse resp) {
        this.requestProcessorIterator = iterator;
        this.request = req;
        this.response = resp;
        this.requestMethod = req.getMethod();
        this.requestPath = req.getPathInfo();
        this.responseCode = HttpServletResponse.SC_OK;
    }

    /**
     * 通过责任链模式来依次调用请求处理器对请求进行处理
     */
    public void doRequestProcessorChain() {
        // 1.通过迭代器遍历注册的请求处理器实现列表
        try {
            while (requestProcessorIterator.hasNext()) {
                RequestProcessor requestProcessor = requestProcessorIterator.next();
                // 2.直到某个请求处理器执行后返回为false为止
                boolean process = requestProcessor.process(this);
                if (!process) {
                    break;
                }
            }
        } catch (Exception e) {
            // 3.期间如果出现异常，则交给内部异常渲染器进行处理
            this.resultRender = new InternalErrorResultRender(e.getMessage());
            log.error("doRequestProcessorChain error:{}", e.getMessage());
        }
    }

    /**
     * 请求结果渲染
     */
    public void doRender() {
        // 1.如果请求处理器实现类均未选择合适的渲染器，就使用默认的
        if (null == this.resultRender) {
            this.resultRender = new DefaultResultRender();
        }
        // 2.调用渲染器的render方法对结果进行渲染
        try {
            resultRender.render(this);
        } catch (Exception e) {
            log.error("doRender error:{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }
}
